package com.logic.modular.gameCore.map.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.comment.pojo.domain.logic.core.CoreCityBuildings;
import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logic.modular.gameCore.map.mapper.CoreCityBuildingsMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 内政建筑(CoreCityBuildings)表服务实现类
 *
 * @author cxy
 * @since 2024-08-01 09:30:45
 */
@Slf4j
@Service
public class CoreCityBuildingsServiceImpl extends ServiceImpl<CoreCityBuildingsMapper, CoreCityBuildings> implements IService<CoreCityBuildings> {
    Cache<String, Map<Long,CoreCityBuildings>> cache = Caffeine.newBuilder().build();
    
    @PostConstruct
    private void init() {
        CoreCityBuildings initSelect = CoreCityBuildings.builder().build();
        List<CoreCityBuildings> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存内政建筑数据,数据量为:{}",list.size());
        cache.put(
                "coreCityBuildings", 
                list.stream().collect(Collectors.toMap(CoreCityBuildings::getId, CoreCityBuildings -> CoreCityBuildings))
        );
        log.info("内政建筑数据缓存完成");
    }

    public List<CoreCityBuildings> listCache() {
        Map<Long,CoreCityBuildings> values = cache.getIfPresent("coreCityBuildings");
        if (Objects.isNull(values)) {
            throw new RuntimeException("内政建筑数据为空");
        }
        return new ArrayList<>(values.values());
    }   
    
    public CoreCityBuildings getCache(Long id) {
        Map<Long,CoreCityBuildings> values = cache.getIfPresent("coreCityBuildings");
        if (Objects.isNull(values)) {
            throw new RuntimeException("内政建筑数据为空");
        }
        return values.get(id);
    }
}
